package com.yumei.trader.gym.page;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.yumei.trader.gym.client.TGApplication;
import androidx.core.content.ContextCompat;
import com.yumei.trader.gym.view.StockConst;
import com.yumei.trader.gym.dbase.sqlite.SqliteActObject;
import com.yumei.trader.gym.util.StringUtils;
import com.yumei.trader.gym.view.element.TicketElement;
import com.yumei.trader.gym.dbase.DBaseConst;
import com.yumei.trader.gym.object.GameObj;
import com.yumei.trader.gym.view.KlineGameView;
import com.yumei.trader.gym.R;
import com.yumei.trader.gym.act.TraderAct;
import com.yumei.trader.gym.client.BasePage;
import com.yumei.trader.gym.raw.GameSoundManager;
import com.yumei.trader.gym.raw.TradeSoundPool;
import com.yumei.trader.gym.view.StockRequest;

import java.util.ArrayList;

public abstract class PlayerBase extends BasePage {

    protected TraderAct mAccount;

    protected StockRequest mTask;
    protected KlineGameView klineView;

    private TextView tvCount;//持股数
    private TextView tvValue; //市值
    private TextView tvRise; //涨幅
    private TextView tvCost; //成本价

    protected ImageButton btnBuy,btnSell;

    protected CheckBox ckPause;

    //复盘退出
    protected ImageButton btnAnalyseExit;

    private boolean exit = false;
    protected int THREAD_TIME = 2000;

    protected long startValue = 0;
    protected long endValue = 0;

    protected ArrayList<GameObj> actions = new ArrayList<>();

    private PowerManager.WakeLock wakeLock;
    private int buyStatus = 0;
    private int sellStatus = 0;

    protected String isOpenVoice,isOpenMusic;

    protected TGApplication mApp;

    @SuppressLint({"InvalidWakeLockTag", "WakelockTimeout"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //界面全屏，隐藏状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        PowerManager manager = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wakeLock = manager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
                PowerManager.ON_AFTER_RELEASE, "ATAAW");
        wakeLock.acquire();

        mApp = (TGApplication)this.getApplication();

        mTask = new StockRequest(this);

    }

    public void onBackPressed(){
        ckPause.setChecked(true);
        showExitAlertDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!exit) {
            ckPause.setChecked(false);
        }

    }

    public void onPause(){
        super.onPause();
        if(!exit) {
            ckPause.setChecked(true);
        }

    }

    protected void registerBaseComponent(){

        isOpenVoice = mApp.getDBMrg().getValue(DBaseConst.Is_Open_Voice, "true");
        isOpenMusic = mApp.getDBMrg().getValue(DBaseConst.Is_Open_Music, "true");

        GameSoundManager.getInstance().setOpenSound(Boolean.parseBoolean(isOpenVoice));


        tvCount = findViewById(R.id.tv_count);
        tvValue = findViewById(R.id.tv_value);
        tvRise = findViewById(R.id.tv_rise);
        tvCost = findViewById(R.id.tv_cost);

        klineView = this.findViewById(R.id.kline_view);

        //暂停
        ckPause = this.findViewById(R.id.ck_pause);
        ckPause.setClickable(false);
        ckPause.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                onPauseAction(b);
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        //交易按钮
        btnBuy = this.findViewById(R.id.btn_buy);
        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnBuy.setClickable(false);
                btnSell.setClickable(false);
                if (buyStatus == 0 && sellStatus == 0){
                    buyStatus = 1;
                }else if (buyStatus == 0 && sellStatus == 2){
                    buyStatus = 2;
                }
                onTraderAction();
            }
        });
        btnSell = this.findViewById(R.id.btn_sell);
        btnSell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnBuy.setClickable(false);
                btnSell.setClickable(false);
                if (buyStatus == 1 && sellStatus == 0){
                    sellStatus = 1;
                }else if (buyStatus == 0 && sellStatus == 0){
                    sellStatus = 2;
                }
                onTraderAction();
            }
        });

        //退出复盘模式
        btnAnalyseExit = this.findViewById(R.id.btn_analyse_exit);
        btnAnalyseExit.setVisibility(View.GONE);
        btnAnalyseExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnAnalyseExit.setVisibility(View.GONE);
                onShowGameResult();
                playSound(TradeSoundPool.ACTION_BUTTON);
                klineView.setReview(false);
            }
        });
    }

    @SuppressLint("DefaultLocale")
    protected void setAccount(TraderAct account){
        startValue = Long.valueOf(String.format("%.0f",account.getValue()));
        this.mAccount = account;
    }

    /**
     * 加载股票数据
     */
    protected void loadStockHisData(){

    }

    /**
     * 买卖交易操作
     */
    private void onTraderAction(){

        if (buyStatus == 0 && sellStatus == 0){
            btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_normal);
            btnSell.setBackgroundResource(R.mipmap.ic_game_sell_normal);
        }else {
            TicketElement ticketEl = klineView.getCurrent();
            int index = StockConst.MAXLEN - klineView.getOffset()-1;
            if (buyStatus == 1 && sellStatus == 0){
                if (mAccount.onBuyAction(ticketEl, index, 0)){
                    actions.add(new GameObj(ticketEl.date, 1, (int)mAccount.getCount()));
                    play(true);
                    onCalculateSystemBS();
                    btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_pressed);
                    btnSell.setBackgroundResource(R.mipmap.ic_game_sell_false);
                }else {
                    showLessDialog();
                }
            }else if (buyStatus == 1 && sellStatus == 1){
                if(mAccount.isBuyIn()) {
                    if (mAccount.onSellAction(ticketEl, index)) {
                        actions.add(new GameObj(ticketEl.date, -1, (int) mAccount.getCount()));
                        play(false);
                        btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_normal);
                        btnSell.setBackgroundResource(R.mipmap.ic_game_sell_normal);
                    }
                }
            }else if (buyStatus == 0 && sellStatus == 2){
                if (mAccount.onBuyAction(ticketEl, index, 1)) {
                    actions.add(new GameObj(ticketEl.date, 1, (int) mAccount.getCount()));
                    play(true);
                    onCalculateSystemBS();
                    btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_false);
                    btnSell.setBackgroundResource(R.mipmap.ic_game_sell_pressed);
                }else {
                    showLessDialog();
                }
            }else if (buyStatus == 2 && sellStatus == 2){
                if(mAccount.isBuyIn()) {
                    if (mAccount.onSellAction(ticketEl, index)) {
                        actions.add(new GameObj(ticketEl.date, -1, (int) mAccount.getCount()));
                        play(false);
                        btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_normal);
                        btnSell.setBackgroundResource(R.mipmap.ic_game_sell_normal);
                    }
                }
            }

            onUpdateAction(ticketEl);
            klineView.repaint();
            btnBuy.setClickable(false);
            btnSell.setClickable(false);
        }
    }

    /**
     * 更新收益
     */
    public void onUpdateAction(TicketElement el){

        mAccount.onUpdateAction(el);
        updateAccountInfo();

        if (buyStatus == 0 && sellStatus == 0){
            btnBuy.setClickable(true);
            btnSell.setClickable(true);
        }else {
            if (buyStatus == 1 && sellStatus == 0){
                btnBuy.setClickable(false);
                btnSell.setClickable(true);
            }else if (buyStatus == 1 && sellStatus == 1){
                buyStatus = 0;
                sellStatus = 0;
                btnBuy.setClickable(true);
                btnSell.setClickable(true);
            }else if (buyStatus == 0 && sellStatus == 2){
                btnBuy.setClickable(true);
                btnSell.setClickable(false);
            }else if (buyStatus == 2 && sellStatus == 2){
                buyStatus = 0;
                sellStatus = 0;
                btnBuy.setClickable(true);
                btnSell.setClickable(true);
            }
        }
    }

    /**
     * 暂停操作
     */
    protected void onPauseAction(boolean pause){

    }

    /**
     * 开始游戏
     */
    protected synchronized void startGame(){

        exit = false;
        btnBuy.setClickable(true);
        btnSell.setClickable(true);
        ckPause.setClickable(true);
        //ckPause.setChecked(false);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!exit){
                    try {
                        if(ckPause.isChecked()){
                            Thread.sleep(200);
                        }else {
                            Message message = new Message();
                            if(klineView.next()) {
                                message.what = 0;
                                message.obj = klineView.getCurrent();
                                handler.sendMessage(message);
                                Thread.sleep(THREAD_TIME);
                            }else{
                                message.what = -1;
                                message.obj = klineView.getCurrent();
                                handler.sendMessage(message);
                                exit = true;
                            }

                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if(msg.what == 0) {
                onUpdateAction((TicketElement) msg.obj);
            }else{
                onOverAction((TicketElement) msg.obj,false);
            }
        }
    };

    /**
     * 更新收益
     */
    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    protected void updateAccountInfo(){

        tvCost.setText(String.format("%.2f", mAccount.getCost()));
        //tvCount.setText(String.valueOf(mAccount.getCount()));

        tvCount.setText(StringUtils.moneyFormat(mAccount.getCount(),0));

        tvRise.setText(String.format("%.2f", mAccount.getRise())+"%");

        /*
        if (mAccount.getCount() < 10000){
            tvCount.setText(String.format("%.0f", mAccount.getCount())+"股");
        }else if (mAccount.getCount() < 100000000){
            tvCount.setText(String.format("%.2f", mAccount.getCount()/10000)+"万股");
        }else {
            tvCount.setText(String.format("%.2f", mAccount.getCount()/100000000)+"亿股");
        }*/

        if(mAccount.getRise() > 0){
            tvRise.setTextColor(ContextCompat.getColor(this, R.color.color_stock_down));
        }else if(mAccount.getRise() < 0){
            tvRise.setTextColor(ContextCompat.getColor(this, R.color.color_stock_up));
        }else{
            tvRise.setTextColor(ContextCompat.getColor(this, R.color.color_font_main));
        }

        endValue = Long.valueOf(String.format("%.0f",mAccount.getValue()));
        tvValue.setText(StringUtils.formatCash(String.format("%.0f",mAccount.getValue()),0));

        if(mAccount.getValue() >= 100000){
            tvValue.setTextColor(ContextCompat.getColor(this, R.color.color_stock_down));
        }else{
            tvValue.setTextColor(ContextCompat.getColor(this, R.color.color_stock_up));
        }

        SqliteActObject.getInstance(this).setAccount(mApp.getUserId(), mAccount.getValue());
    }

    /**
     * 游戏结束
     */
    protected void onOverAction(TicketElement el, boolean exit){

        if(el == null) return;

        if(mAccount.isBuyIn()){
            if(mAccount.onSellAction(el,0)){
                onUpdateAction(el);
                btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_normal);
                btnBuy.setClickable(true);
                btnSell.setBackgroundResource(R.mipmap.ic_game_sell_normal);
                btnSell.setClickable(true);
            }
        }
        klineView.repaint();

        if(!exit) {
            onGameResultAction(mAccount);
        }
    }

    /**
     * 显示成绩界面
     */
    protected void  onShowGameResult(){

    }

    /**
     * 退出提示
     */
    protected void showExitAlertDialog(){

        View contentView = inflate(R.layout.pop_game_exit);
        final PopupWindow popup = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,true);

        Button btnOk = contentView.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
                onOverAction(klineView.getCurrent(),true);
                playSound(TradeSoundPool.ACTION_BUTTON);
                onBackAction();
            }
        });

        Button btnCancel = contentView.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        if(!isFinishing()) {
            popup.setAnimationStyle(R.style.pop_animation);
            popup.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        }
    }

    protected void showLessDialog(){
        ckPause.setChecked(true);
        View contentView = inflate(R.layout.pop_game_message);
        View contentLayout = contentView.findViewById(R.id.popup_content_layout);
        final PopupWindow popup = new PopupWindow(contentLayout, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,true);

        Button btnOk = contentView.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
                onOverAction(klineView.getCurrent(),true);
                playSound(TradeSoundPool.ACTION_BUTTON);
                onBackAction();
            }
        });

        Button btnCancel = contentView.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        if(!isFinishing()) {
            popup.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(wakeLock != null){
            wakeLock.release();
            wakeLock= null;
        }
    }

    //计算系统买卖信号
    protected abstract void onCalculateSystemBS();
    //游戏结果
    protected abstract void onGameResultAction(TraderAct account);

    protected  void playSound(int mode){
        GameSoundManager.getInstance().getSoundPool(this).play(mode);
    }

    private void  play(boolean buy){

        System.out.println("voice=" + isOpenVoice);

        if(isOpenVoice.equals("true")){
            if(buy) {
                GameSoundManager.getInstance().getSoundPool(this).play(TradeSoundPool.ACTION_BUY);
            }else{
                GameSoundManager.getInstance().getSoundPool(this).play(TradeSoundPool.ACTION_SELL);
            }
        }
    }
}

